<?php

namespace App\Http\Controllers;

use App\Activity;
use App\Activityable;
use App\Order;
use Illuminate\Http\Request;

class OrderController extends Controller {
	use Search;

	protected $model, $map, $activity;

	public function __construct(Order $order, Activityable $activityable, Activity $activity) {
		$this->model = $order;
		$this->map = $activityable;
		$this->activity = $activity;
	}

	public function index(Request $request) {
		session('order-list-where', null);
		$business = $this->getBusiness();
		return view('orders.index', compact('business', 'nums'));
	}

	public function list(Request $request) {
		$page = $request->get('page', 1);
		$pageSize = $request->get('pageSize', 10);
		$where = $this->getSearchWhere($request);
		session('order-list-where', $where);
		$nums['orderNum'] = $this->model->whereRaw($where)->count();
		$nums['sendOrderNum'] = $this->model->whereRaw($where . ' and type = 1')->count();
		$pageNums = ceil($nums['orderNum'] / $pageSize);
		$orders = $this->model->whereRaw($where)->offset(($page - 1) * $pageSize)->limit($pageSize)->get();
		return view('orders.list', compact('orders', 'page', 'pageNums', 'nums'));
	}

	public function detail($id) {
		$order = $this->model->findOrFail($id);
		return view('orders.detail', compact('order'));
	}

	public function import() {
		$business = $this->getBusiness(true);
		return view('orders.import', compact('business'));
	}

	public function destroy($ids) {
		if ($ids != 'all') {
			if (!is_numeric($ids)) {
				$ids_list = array_merge(array_filter(explode(',', $ids), function ($value) {
					return is_numeric($value);
				}));
				if (empty($ids_list)) {
					return ['code' => 1, 'msg' => 'no item be checked'];
				}
			}
		}
		$where = $ids == 'all' ? session('order-list-where') : ' id in (' . $ids . ')';
		$this->model->whereRaw($where)->delete();
		return ['code' => 0, 'msg' => 'success'];
	}
}
